<template>
  <div class="chat-header">
    <div class="header-content">
      <div class="left-content">
        <a-space align="center">
          <a-avatar v-if="GroupStore.avatarMaxUrl">
            <img alt="avatar" :src="GroupStore.avatarMaxUrl" />
          </a-avatar>
          <a-avatar v-else>
            <icon-user-group />
          </a-avatar>
          <span class="friend-name">{{ GroupStore.groupnick }}</span>
        </a-space>
      </div>
      <div class="search-content">
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="输入关键词"
          v-model="keyword"
          search-button
          @search="handleSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
          <template #button-default> 消息搜索 </template>
        </a-input-search>
      </div>
      <div class="right-content">
        <a-tooltip content="刷新消息"
          ><a-button type="text" size="small" @click="getmsglist">
            <template #icon><icon-refresh /></template> </a-button
        ></a-tooltip>
        <a-tooltip content="清空消息"
          ><a-popconfirm content="此操作不可恢复，请谨慎操作！" position="br" type="warning" @ok="delmsglist"><a-button type="text" size="small">
            <template #icon><icon-delete /></template> </a-button
        ></a-popconfirm></a-tooltip>
      </div>
    </div>
  </div>
  <a-table
    :data="chatMessages"
    :columns="columns"
    :loading="loading"
    :pagination="{
      total: count,
      current: current,
      pageSize: pageSize,
      showTotal: true,
      showPageSize: true,
    }"
    :row-selection="{
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    }"
    v-model:selectedKeys="selectedKeys"
    @page-change="handlePageChange"
    @page-size-change="handlePageSizeChange"
  >
    <template #type="{ record }">
      <a-tag color="orange" v-if="record.direction === 'send'">发送</a-tag>
      <a-tag color="gray" v-if="record.direction === 'receive'">收到</a-tag>
    </template>
    <template #content="{ record }">
      <a-typography-paragraph
        :ellipsis="{
          rows: 2,
          expandable: true,
          ellipsisStr: true,
        }"
        style="white-space: pre-line"
      >
        <template v-if="processContent(record.content).type === 'image'">
          {{ processContent(record.content).url }}
        </template>
        <template v-else>
          {{ processContent(record.content).content }}
        </template>
      </a-typography-paragraph>
    </template>
    <template #time="{ record }">
      <div>{{ formatTime(record.timestamp) }}</div>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
  import { ref, defineProps, watch } from 'vue';
  import { useGroupStore } from '@/store';
  import { Message } from '@arco-design/web-vue';
  import type { TableColumnData } from '@arco-design/web-vue';
  import { showroommsg, delroommsg } from '@/api/chat';
  import dayjs from 'dayjs';

  const props = defineProps<{
    selectedWxid: string;
    selectedAvatar: string;
  }>();
  const GroupStore = useGroupStore();
  // 分页相关
  const current = ref(1);
  const pageSize = ref(20);
  const count = ref(0);
  const loading = ref(false);
  const selectedKeys = ref<string[]>([]);
  const keyword = ref('');
  const columns: TableColumnData[] = [
    {
      title: '类型',
      slotName: 'type',
      width: 80,
      align: 'center',
    },
    {
      title: '时间',
      slotName: 'time',
      width: 200,
    },
    {
      title: '内容',
      slotName: 'content',
    },
  ];
  // 组件状态
  const chatMessages = ref<any[]>([]);
  // 格式化时间
  const formatTime = (timestamp: number) => {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
  };

  // 获取消息列表
  const getmsglist = async () => {
    loading.value = true;
    try {
      const res: any = await showroommsg({
        selectedWxid: props.selectedWxid,
        groupwxid: GroupStore.groupwxid,
        page: current.value,
        pageSize: pageSize.value,
        field: {
          msg: keyword.value,
        }, // 传递 keyword 参数
      });

      if (res.code === 20000) {
        // 设置消息列表
        chatMessages.value = res.data.messages || [];
        count.value = res.data.pagination.total;
        loading.value = false;
      } else {
        Message.error(res.msg || '获取消息失败');
      }
    } catch (error) {
      Message.error('获取消息失败');
    }
  };

  const handleSearch = () => {
    current.value = 1; // 重置为第一页
    getmsglist();
  };

  // 处理页码改变
  const handlePageChange = async (page: number) => {
    current.value = page;
    await getmsglist();
  };

  // 处理每页数量改变
  const handlePageSizeChange = async (size: number) => {
    current.value = 1; // 切换每页数量时重置为第一页
    pageSize.value = size;
    await getmsglist();
  };

  // 添加处理消息内容的方法
  const processContent = (content: string) => {
    if (!content) return { type: 'text', content: '' };

    // 检查是否包含图片
    if (content.includes('pic=')) {
      // 提取 pic= 到第一个逗号之间的内容作为图片 URL
      const startIndex = content.indexOf('pic=') + 4;
      const endIndex = content.indexOf(',', startIndex);
      const imageUrl = content.substring(
        startIndex,
        endIndex > -1 ? endIndex : undefined
      );
      return {
        type: 'image',
        url: imageUrl,
      };
    }

    // 使用属性简写语法
    return {
      type: 'text',
      // 当属性名和值的变量名相同时，可以简写
      content,
    };
  };

  const delmsglist = async () => {
    const mywxid = props.selectedWxid;
    const fromWxid = GroupStore.groupwxid;

    if (!mywxid || !fromWxid) {
      Message.warning('参数不完整，无法删除');
      return;
    }

    try {
      const res: any = await delroommsg({
        selectedWxid: mywxid,
        groupwxid: fromWxid,
      });

      if (res.code === 20000) {
        Message.success('消息删除成功');
        getmsglist(); // 刷新列表
      } else {
        Message.error(res.msg || '消息删除失败');
      }
    } catch (error) {
      Message.error('请求失败，请重试');
      console.error('删除消息失败:', error);
    }
  };

  // 监听群变化
  watch(
    () => GroupStore.groupwxid,
    (newWxid) => {
      if (newWxid) {
        chatMessages.value = [];
        getmsglist(); // 获取新的聊天记录
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .chat-header {
    display: flex;
    padding: 10px;
    width: 100%;
    border: 1px solid var(--color-border);
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .left-content {
    display: flex;
    align-items: center;
  }

  .right-content {
    display: flex;
    align-items: center;
  }

  .friend-name {
    margin-left: 8px;
    font-weight: 500;
  }
</style>
